package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.dto.AddressDto;
import cn.edu.tju.elm.model.DeliveryAddress;
import cn.edu.tju.elm.repository.DeliveryAddressRepository;
//import cn.edu.tju.elb.service.AddressService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api")
@Tag(name="管理地址", description = "对配送地址的增删改查")
public class AddressController {
//    @Autowired
//    private AddressService addressService;

    @Autowired
    private final UserService userService;
    private final DeliveryAddressRepository deliveryAddressRepository;

    @Autowired
    public AddressController(UserService userService, DeliveryAddressRepository deliveryAddressRepository) {
        this.userService = userService;
        this.deliveryAddressRepository = deliveryAddressRepository;
    }

    @PostMapping("/addresses")
    @Operation(summary = "为当前用户新增一个配送地址")
    public HttpResult<DeliveryAddress> addDeliveryAddress(@RequestBody AddressDto addressDto) {
        // 1. 获取当前登录的用户
        User currentUser = userService.getUserWithAuthorities()
                .orElseThrow(() -> new AccessDeniedException("用户未登录"));

        // 2. 创建一个新的 DeliveryAddress 实体
        DeliveryAddress newAddress = new DeliveryAddress();

        // 3. 将 DTO 中的数据和当前用户信息填充到新实体中
        newAddress.setContactName(addressDto.getContactName());
        newAddress.setContactSex(addressDto.getContactSex());
        newAddress.setContactTel(addressDto.getContactTel());
        newAddress.setAddress(addressDto.getAddress());
        newAddress.setCustomer(currentUser); // 关联到当前用户

        // 4. 设置审计字段
        newAddress.setCreator(currentUser.getId());
        newAddress.setUpdater(currentUser.getId());
        newAddress.setCreateTime(LocalDateTime.now());
        newAddress.setUpdateTime(LocalDateTime.now());
        newAddress.setDeleted(false);

        // 5. 保存到数据库
        DeliveryAddress savedAddress = deliveryAddressRepository.save(newAddress);

        // 6. 返回成功响应
        return HttpResult.success(savedAddress);
    }

    @GetMapping("/addresses")
    @Operation(summary = "获取当前用户的所有配送地址")
    public HttpResult<List<DeliveryAddress>> getUserAddresses() {
        // 1. 获取当前登录的用户
        User currentUser = userService.getUserWithAuthorities()
                .orElseThrow(() -> new AccessDeniedException("用户未登录"));

        // 2. 查询该用户的所有配送地址
        List<DeliveryAddress> addresses = deliveryAddressRepository.findByCustomerId(currentUser.getId());

        // 3. 返回地址列表
        return HttpResult.success(addresses);
    }

    @PutMapping("/addresses/{addressId}")
    @Operation(summary = "更新指定的配送地址")
    public HttpResult<DeliveryAddress> updateDeliveryAddress(@PathVariable Long addressId, @RequestBody AddressDto addressDto) {
        // 1. 获取当前登录的用户
        User currentUser = userService.getUserWithAuthorities()
                .orElseThrow(() -> new AccessDeniedException("用户未登录"));

        // 2. 查找要修改的地址，并确认是当前用户的地址
        DeliveryAddress address = deliveryAddressRepository.findById(addressId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "配送地址不存在"));

        // 3. 确认是当前用户的地址
        if (!address.getCustomer().getId().equals(currentUser.getId())) {
            throw new AccessDeniedException("无权修改他人的配送地址");
        }

        // 4. 更新地址信息
        address.setContactName(addressDto.getContactName());
        address.setContactSex(addressDto.getContactSex());
        address.setContactTel(addressDto.getContactTel());
        address.setAddress(addressDto.getAddress());
        
        // 5. 更新审计字段
        address.setUpdater(currentUser.getId());
        address.setUpdateTime(LocalDateTime.now());

        // 6. 保存到数据库并返回
        DeliveryAddress updatedAddress = deliveryAddressRepository.save(address);
        return HttpResult.success(updatedAddress);
    }

    @DeleteMapping("/addresses/{addressId}")
    @Operation(summary = "删除指定的配送地址")
    public HttpResult<?> deleteDeliveryAddress(@PathVariable Long addressId) {
        // 1. 获取当前登录的用户
        User currentUser = userService.getUserWithAuthorities()
                .orElseThrow(() -> new AccessDeniedException("用户未登录"));

        // 2. 查找要删除的地址，并确认是当前用户的地址
        DeliveryAddress address = deliveryAddressRepository.findById(addressId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "配送地址不存在"));

        // 3. 确认是当前用户的地址
        if (!address.getCustomer().getId().equals(currentUser.getId())) {
            throw new AccessDeniedException("无权删除他人的配送地址");
        }

        // 4. 删除地址
        deliveryAddressRepository.delete(address);
        
        // 5. 返回成功响应
        return HttpResult.success("配送地址删除成功");
    }
}
